import java.awt.*;
import java.awt.image.*;

public class ButtonPanel extends Panel implements Runnable
{
	MainFrame mf = null;
	BufferedImage iBuf = null;
	Graphics gBuf = null;
	Thread t = null;
	boolean running = false;
	int w,h,aw,ah,i,j;
	int cx,cy,sx,sy;

	public ButtonPanel(MainFrame mainframe,int w,int h)
	{
		super();
		mf = mainframe;
		this.w = w;
		this.h = h;
		aw = w * mf.imgs[0].length;
		ah = h * mf.imgs.length;
		iBuf = new BufferedImage(aw,ah,BufferedImage.TYPE_INT_RGB);
		gBuf = iBuf.getGraphics();
		sx = sy = cx = cy = 0;
		t = new Thread(this,"ButtonPanel");
	}

	void start()
	{
		running = true;
		t.start();
	}

	void stop()
	{
		running = false;
	}


	void mouseMoved(int mx,int my)
	{
		if ((mx >= 0) && (mx < aw))
			cx = (int)(mx / w);
		if ((my >= 0) && (my < ah))
			cy = (int)(my / h);
	}

	void mousePressed(int mx,int my)
	{
		int nx = sx;
		int ny = sy; 
		if ((mx >= 0) && (mx < aw))
			nx = (int)(mx / w);
		if ((my >= 0) && (my < ah))
			ny = (int)(my / h);
		if (mf.imgs[ny][nx] != null)
		{
			sx = nx;
			sy = ny;
		}
	}

	public void redraw()
	{
		try
		{
			Graphics g = getGraphics();
			if (g != null)
			{
				for (i = 0; i < mf.imgs.length; i++)
				for (j = 0; j < mf.imgs[0].length; j++)
				{
					if ((sx == j) && (sy == i))
						gBuf.drawImage(mf.bon,j * w,i * h,null);
					else
						gBuf.drawImage(mf.boff,j * w,i * h,null);

					if (mf.imgs[i][j] != null)
						gBuf.drawImage(mf.imgs[i][j],j * w,i * h,null);
					if ((cx == j) && (cy == i))
					{
						gBuf.setColor(new Color(60,60,80));
						gBuf.drawRect(j * w, i * h,w - 1,h - 1);
					}
				}
   	
				g.setClip(0,0,aw,ah);
				g.drawImage(iBuf,0,0,null);
			}
		}
		catch(Exception ex){}
	}

   public void paint(Graphics g)
   {
      redraw();
   }

   public void run()
   {
   		while (running)
   		{
   			try
   			{
   				t.sleep(50);
   			}
   			catch(Exception ex){}
   			redraw();
   		}
   }
}